#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

#define NUM 1024
#define SIZE 64
#define SEP " "
#define __DEBUG__ 1

#define NoneRedir   0
#define OutputRedir 1
#define AppendRedir 2
#define InputRedir  3

int redir = NoneRedir;
char* filename = NULL;

char cwd[1024];
int lastcode = 0;

const char* getUsername() 
{
    const char* name = getenv("USER");
    if(name) return name;
    else return "none";
}

const char* getHostname() 
{
    const char* hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "none";
}

const char* getCwd() 
{
    const char* cwd = getenv("PWD");
    if(cwd) return cwd;
    else return "none";
}

int getUserCommand(char* userCommand, int size) 
{
    printf("[%s@%s %s]$# ", getUsername(), getHostname(), getCwd());
    char* ret = fgets(userCommand, size, stdin);//会读到表示输入结束的\n
    if(ret == NULL) return -1;
    userCommand[strlen(userCommand)-1] = '\0';//清掉\n
    return strlen(userCommand);
}

void commandSplit(char* in, char* out[])
{
    int argc = 0;
    out[argc++] = strtok(in, SEP);
    while(out[argc++] = strtok(NULL, SEP));
    //char* buf = NULL;
    //for(out[argc++] = strtok(in, SEP); buf = strtok(NULL, SEP); out[argc++] = buf);
#ifdef __DEBUG__
    for(int i = 0; out[i]; i++)
    {
        printf("%s\n", out[i]);
    }
#endif
}

int execute(char* argv[])
{
    pid_t id = fork();
    if(id < 0) return -1;
    else if(id == 0) 
    {
        int fd = 0;
        if(redir == InputRedir) 
        {
            fd = open(filename, O_RDONLY); //输入重定向
            dup2(fd, 0);
        } 
        else if(redir == OutputRedir) 
        {
            fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC); //输出重定向
            dup2(fd, 1);
        } 
        else if(redir == AppendRedir) 
        {
            fd = open(filename, O_WRONLY | O_CREAT | O_APPEND); //追加重定向
            dup2(fd, 1);
        }
        execvp(argv[0], argv);//程序替换
        exit(1);
    }
    else 
    {
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        if(rid > 0) 
        {
            lastcode = WEXITSTATUS(status);
        }
    }
    return 0;
}

//内建命令，就是shsell中的一个函数
void cd(const char* path)
{
    chdir(path);
    char tmp[1024];
    getcwd(tmp, sizeof(tmp));
    sprintf(cwd, "PWD=%s", tmp);
    putenv(cwd);
}

//1->true 0->false 
int doBuildIn(char* argv[])
{
    if(strcmp(argv[0], "cd") == 0)
    {
        char* path = NULL;
        if(argv[1] == NULL) path = ".";
        else path = argv[1];
        cd(path);
        return 1;
    }
    //if(...) 可添加更多内建命令
    return 0;
}

// 宏函数用do {  } while(0)无分号包裹，避免语法报错 
#define SkipSpace(pos) do { while(isspace(*pos)) pos++; } while(0)   

void checkRedir(char userCommand[], int len)
{
    // ls -a -l > log.txt
    char* end = userCommand + len - 1;
    char* start = userCommand;
    while(end > start) 
    {
        if(*end == '>')
        {
            if((*end - 1) == '>')
            {
                *(end - 1) = '\0';
                filename = end + 1;
                SkipSpace(filename);
                redir = AppendRedir;
                break;
            }
            else 
            {
                *end = '\0';
                filename = end + 1;
                SkipSpace(filename);
                redir = OutputRedir;
                break;
            }
        }
        else if(*end == '<')
        {
            *end = '\0';
            filename = end + 1;
            SkipSpace(filename);
            redir = InputRedir;
            break;
        }
        else
        {
            end--;
        }
    }
}

int main()
{
    while(1) 
    {
        char userCommand[NUM];
        char* argv[SIZE];

        //打印提示符 + 获取命令字符串
        int len = getUserCommand(userCommand, sizeof(userCommand));
        if(len <= 0) continue;

        //判断是否有重定向 "ls -a -l" ">" "log.txt" | "指令" "重定向类型" "文件"
        checkRedir(userCommand, strlen(userCommand));

        //分割命令行字符串
        commandSplit(userCommand, argv);

        //查看是否为内建命令
        int cmdType = doBuildIn(argv);
        if(cmdType == 1) continue;

        //执行命令
        execute(argv);
    }    
    return 0;
}

